<?php
/**
 * Created by PhpStorm.
 * User: s.utkin
 * Date: 01.09.14
 * Time: 15:26
 */

namespace NotificationDelivery\Workers;


use NotificationDelivery\Delivery\PushStream;
use NotificationDelivery\Queue\Worker;


class SendToReceiverAction extends Worker
{
    /**
     * Отправляет пачку уведомлений браузеру пользователя через push канал
     */
    public function run()
    {
        $successList = [];

		$tmpItems = [];
		foreach ($this->items as $item) {
			if (empty($item->subscriber)) {
				continue;
			}

			$tmpItems[$item->subscriber][] = $item;
		}

		$this->items = $tmpItems;
		$tmpItems = null;


        # Перебираем массив получателей
        foreach ($this->items as $subscriber => $items) {

            if ($subscriber == 0) {
                continue;
            }

            $pushStream = new PushStream($subscriber);

            # Перебираем массив уведомлений получателя
            /** @var \Pinenut\Queue\ProcessingQueue[] $items */
            foreach ($items as $item) {
                $pushStream->addMessage(json_encode($item->data));
                $successList[] = (string)$item;
            }

            $pushStream->publish();
        }

        return $this->response->successList = $successList;
    }
}